package qeb.handheldmedical.patient;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import cn.bingoogolapple.androidcommon.adapter.BGABindingRecyclerViewAdapter;
import qeb.handheldmedical.R;
import qeb.handheldmedical.databinding.ItemMedicineListBinding;
import qeb.handheldmedical.dialog.DialogUtils;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.Medicine;
import qeb.handheldmedical.model.User;
import qeb.handheldmedical.patient.merge.MedicineC;
import qeb.handheldmedical.patient.merge.MedicineListAdapter;

public class MedicineListActivity extends Activity implements View.OnClickListener {
    private Button mBtnSx;
    private TextView mTvTitle;
    private TextView mTvTitle1;
    private LRecyclerView mRecycleView;

    private User usr = new User();
    public static final String BAR_READ_ACTION = "SYSTEM_BAR_READ";// 条码广播
    public static final String RFID_READ_ACTION = "SYSTEM_RFID_READ";// RFID广播
    public static final String NLSCAN_SCANNER = "nlscan.action.SCANNER_RESULT";// 新大陆机型
    public String action;// 扫描
    private BroadcastReceiver InPatientListReciever;
    // honeywell
    private final static String TAG = "ScanResultReceiver";
    private static final String INTENT_ACTION_SCAN_RESULT = "com.honeywell.tools.action.scan_result";
    private static final String SCANACTION = "com.android.server.scannerservice.broadcastxhyy";// 小码哥
    private static final String Neusoft = "com.neusoft.action.scanner.read";// 东软
    private Medicine medicine ;
    private MultiDialog mDialog;
    private View emptyView;
    //ALL的Task
    public ArrayList<MedicineC> mMedicines;
    private MedicineListAdapter mAdapter;
    public BGABindingRecyclerViewAdapter<Medicine, ItemMedicineListBinding> alllinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_medicine_list);
    public LRecyclerViewAdapter allAdapter ;
    private Toast tt;
    private JSONArray datas;
    private  List<MedicineC> list;
    public void setDate(boolean isRefresh,List<MedicineC> datas){
        if(null == mMedicines){
            mMedicines = new ArrayList<>();
        }
        if(isRefresh){
            mAdapter.setDates(datas);
            allAdapter.removeFooterView();
            allAdapter.removeHeaderView();
            allAdapter.notifyDataSetChanged();
            mRecycleView.refreshComplete(10);
        }else{
            mAdapter.addMoreDate(datas);
            allAdapter.removeFooterView();
            allAdapter.removeHeaderView();
            allAdapter.notifyDataSetChanged();
            mRecycleView.refreshComplete(10);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medicine_list);
        usr = (User) getIntent().getSerializableExtra("userinfo");

        mAdapter = new MedicineListAdapter(MedicineListActivity.this);
        allAdapter = new LRecyclerViewAdapter(mAdapter);
        initView();
        initDate();
        initBarReciever();

    }

    private void initView() {
        mBtnSx =  findViewById(R.id.btn_sx);
        mTvTitle =  findViewById(R.id.tv_title);
        mTvTitle1 =  findViewById(R.id.tv_title1);
        if(!TextUtils.isEmpty(usr.DNAME)){
            mTvTitle1.setText(usr.DNAME);
        }
        mRecycleView =  findViewById(R.id.recycler);
        mBtnSx.setOnClickListener(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecycleView.setLayoutManager(manager);
        mRecycleView.setAdapter(allAdapter);
//
        mRecycleView.setPullRefreshEnabled(true);
        mRecycleView.setLoadMoreEnabled(true);
        mRecycleView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); //设置下拉刷新Progress的样式
        mRecycleView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);  //设置下拉刷新箭头
        mRecycleView.setHeaderViewColor(R.color.colorAccent, R.color.appText3, android.R.color.white);
        mRecycleView.setFooterViewColor(R.color.colorAccent, R.color.appText3, android.R.color.white);
        //设置底部加载文字提示
        mRecycleView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //设置底部加载文字提示
        mRecycleView.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");
//        mRecycleView.addItemDecoration(new SimpleItemDecoration(this, SimpleItemDecoration.VERTICAL_LIST));
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMedListByPzsj(true);
            }
        });

        mRecycleView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getMedListByPzsj(false);
            }
        });
        mRecycleView.refresh();
    }

    public  boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(InPatientListReciever, filter);
//        getMedListByPzsj(true);
        super.onResume();
    }
    @Override
    protected void onRestart() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(InPatientListReciever, filter);
        super.onRestart();
    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        MedicineListActivity.this.unregisterReceiver(InPatientListReciever);

        super.onPause();
    }
    private void initBarReciever() {

        InPatientListReciever = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                action = intent.getAction();
                Log.d("scan", "MedicineListActivity");
                String BAR_value = "";
                String STATE_value = "ok";

                if (action.equals(BAR_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("BAR_VALUE").trim();
                } else if (action.equals(RFID_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("RFID_VALUE").trim();
                } else if (action.equals(INTENT_ACTION_SCAN_RESULT)) {
                    if (intent.hasExtra("decode_rslt")) {
                        BAR_value = intent.getStringExtra("decode_rslt");
                    }
                } else if (action.equals(SCANACTION)) {
                    BAR_value = intent.getStringExtra("scannerdata").replaceAll("\r|\n", "");
                } else if (action.equals(Neusoft)) {
                    BAR_value = intent.getStringExtra("scanner_value").replaceAll("\r|\n", "");
                } else if (action.equals(NLSCAN_SCANNER)) {
                    STATE_value = intent.getStringExtra("SCAN_STATE");
                    BAR_value = TextUtils.isEmpty(intent.getStringExtra("SCAN_BARCODE1")) ? intent.getStringExtra("SCAN_BARCODE2") : intent.getStringExtra("SCAN_BARCODE1");
                    BAR_value = BAR_value.replaceAll("\r|\n", "");
                }
                if (!BAR_value.equals("ERROR") || STATE_value.equals("ok")) {// 扫描出错
                    if (!isInteger(BAR_value.substring(0,2))){
                        //  根据药品条码获取药品信息
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("ywbqtm", BAR_value);

                        JSONObject resultObject = WSHelper.getWebserviceJsonObject(
                                "GetMedInfoByYptm", map);
                        if (resultObject != null) {
                            // 弹框
                            medicine = new Gson().fromJson(resultObject.toString(),Medicine.class);
                            try {
//                                medicine.getValue(resultObject);
                                String state ;
                                if(medicine.getYwpzzt().equals("0")){
                                    state ="未配置";
                                }else{
                                    state ="已配置";
                                }
                                Map<String, String> map2 = new HashMap<String, String>();
                                map2.put("ywbqtm", medicine.ywbqtm);
                                map2.put("ywpzrybh", usr.GH);
                                String result = WSHelper.getWebserviceString("UpdateMedState",map2);
                                if(!TextUtils.isEmpty(result)){
                                    if("药物配置成功".equals(result)){
                                        medicine.setYwpzzt("1");
                                        medicine.setYwpzsj(getCurrFullDay());
                                        // 重新获取列表数据
                                        getMedListByPzsj(true);
                                        TipHelper.Vibrate(MedicineListActivity.this,600);
                                    }
                                    tt = Toast.makeText(MedicineListActivity.this,
                                            result, Toast.LENGTH_LONG);
                                    tt.show();
                                }
                                else{
                                    tt = Toast.makeText(MedicineListActivity.this,
                                            "执行失败，请重试！", Toast.LENGTH_LONG);
                                    tt.show();
                                }
//                                mDialog = new MultiDialog(MedicineListActivity.this,
//                                        MultiDialog.DialogType.CONFIRM);
//                                mDialog.setTitle("是否执行");
//                                mDialog.setMessage(medicine.getYwMc()+"\n"+medicine.getYwgg()+"\n"+"患者姓名:"+medicine.getHzname()+"\n"+"配置时间:" +medicine.getYwpzsj()+"\n"+"配置状态: "+state);
//                                mDialog.setDialogGoListener(new View.OnClickListener(){
//
//                                    Toast tt;
//                                    @Override
//                                    public void onClick(View arg0) {
//                                        // TODO Auto-generated method stub
//                                        Map<String, String> map = new HashMap<String, String>();
//                                        map.put("ywbqtm", medicine.ywbqtm);
//                                        map.put("ywpzrybh", usr.GH);
//                                        String result = WSHelper.getWebserviceString("UpdateMedState",map);
//                                        if(!TextUtils.isEmpty(result)){
//                                            if("药物配置成功".equals(result)){
//                                                medicine.setYwpzzt("1");
//                                                medicine.setYwpzsj(getCurrFullDay());
//                                                addDate(medicine);
//                                            }
//                                            tt = Toast.makeText(MedicineListActivity.this,
//                                                    result, Toast.LENGTH_LONG);
//                                            tt.show();
//                                            mDialog.cancel();
//                                        }
//                                        else{
//                                            tt = Toast.makeText(MedicineListActivity.this,
//                                                    "执行失败，请重试！", Toast.LENGTH_LONG);
//                                            tt.show();
//                                            mDialog.cancel();
//                                        }
//
//                                    }
//
//                                });
//                                mDialog.show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
//                        else {
//                            Toast tt = Toast.makeText(MedicineListActivity.this,
//                                    "该条码没有找到对应的药品信息！", Toast.LENGTH_LONG);
//                            tt.show();
//                            tt.setGravity(Gravity.CENTER, 0, 0);
//                        }
                    }
                } else {
                    Toast tt = Toast.makeText(MedicineListActivity.this, "扫描出错！", Toast.LENGTH_LONG);
                    tt.show();
                    tt.setGravity(Gravity.CENTER, 0, 0);
                }
            }

        };
    }
    public  String getCurrFullDay() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return sDateFormat.format(new Date());
    }
    private void initDate() {
//        mRecycleView.setLoadMoreFooter(new ILoadMoreFooter() {
//            @Override
//            public void onReset() {
//
//            }
//
//            @Override
//            public void onLoading() {
//                getMedListByPzsj(false);
//            }
//
//            @Override
//            public void onComplete() {
//                allAdapter.removeFooterView();
//            }
//
//            @Override
//            public void onNoMore() {
//                allAdapter.removeFooterView();
//
//
//
//            }
//
//            @Override
//            public View getFootView() {
//                return LayoutInflater.from(getContext()).inflate(R.layout.activity_main_foot, null, false);
//            }
//        });
//        mRecycleView.addOnScrollListener(new onLoadMoreListener() {
//            @Override
//            protected void onLoading(int countItem,int lastItem) {
//              //请求下一页数据
//                getMedListByPzsj(false);
//            }
//        });

    }
    private int pageIndex = 1;
    private final int pageSize  = 10;
    public void getMedListByPzsj(boolean isRefresh){
        if(isRefresh){
            pageIndex = 1;
        }else{
            ++ pageIndex;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("pzsj", getCurrFullDay());
        map.put("pageIndex",pageIndex+"");
        map.put("pageSize",pageSize+"");
        if (!isRefresh){
            DialogUtils.waitingDialog(MedicineListActivity.this);
        }
        datas = WSHelper.getWebserviceFun("GetMedListByPzsj",
                map);

        //如果下拉加载更多没数据，就加一个结尾
        if(null == datas && !isRefresh){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
            allAdapter.addFooterView(view);
            return;
        }
        if(null != datas && datas.length()>0){
            list= new Gson().fromJson(datas.toString(), new TypeToken<List<MedicineC>>() {}.getType());
            if(null != list){
                DialogUtils.dismiss(MedicineListActivity.this);
                setDate(isRefresh,list);
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_sx:
                onBackPressed();
                break;
        }
    }
}
